// SPDX-FileCopyrightText: Copyright 2025-2025 深圳市同心圆网络有限公司
// SPDX-License-Identifier: GPL-3.0-only

package config_cmd

import (
	"fmt"
	"os"
	"os/user"

	"gitcode.com/openseaotter/so_server/config"
	"gitcode.com/openseaotter/so_server/utils"
	"github.com/dchest/uniuri"
	"github.com/spf13/cobra"
)

var initCfgCmd_Force bool
var initCfgCmd_TlsCertFile string
var initCfgCmd_TlsKeyFile string
var initCfgCmd_Domain string

var initCfgCmd = &cobra.Command{
	Use: "init",
	RunE: func(cmd *cobra.Command, args []string) error {
		//检查是否是root用户
		curUser, err := user.Current()
		if err != nil {
			return err
		}
		if curUser.Uid != "0" {
			return fmt.Errorf("need root to run this command")
		}

		_, err = os.Stat(utils.CONFIG_FILE_PATH)
		if err == nil && !initCfgCmd_Force {
			return fmt.Errorf("config file exist,please use --force flag")
		}
		tlsPort := uint16(0)
		certFilePath := ""
		keyFilePath := ""
		if initCfgCmd_TlsCertFile != "" && initCfgCmd_TlsKeyFile != "" {
			tlsPort = uint16(443)
			certFilePath = utils.CONFIG_TLS_CERT_FILE_PATH
			keyFilePath = utils.CONFIG_TLS_KEY_FILE_PATH
		}

		cfg := &config.ServerConfig{
			Domain:      initCfgCmd_Domain,
			SuperToken:  uniuri.NewLenChars(32, []byte("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")),
			ServicePort: 6004,
			HttpPort:    80,
			HttpTlsPort: tlsPort,
			TlsCertFile: certFilePath,
			TlsKeyFile:  keyFilePath,
			RemoteList:  []*config.RemoteConfig{},
		}
		err = config.WriteServerConfig(cfg)
		if err != nil {
			return err
		}
		uid, gid, err := utils.GetUidAndGid()
		if err != nil {
			return err
		}
		if initCfgCmd_TlsCertFile != "" {
			data, err := os.ReadFile(initCfgCmd_TlsCertFile)
			if err != nil {
				return err
			}
			err = os.WriteFile(utils.CONFIG_TLS_CERT_FILE_PATH, data, 0600)
			if err != nil {
				return err
			}
			os.Chown(utils.CONFIG_TLS_CERT_FILE_PATH, uid, gid) //skip error check
		}
		if initCfgCmd_TlsKeyFile != "" {
			data, err := os.ReadFile(initCfgCmd_TlsKeyFile)
			if err != nil {
				return err
			}
			err = os.WriteFile(utils.CONFIG_TLS_KEY_FILE_PATH, data, 0600)
			if err != nil {
				return err
			}
			os.Chown(utils.CONFIG_TLS_KEY_FILE_PATH, uid, gid) //skip error check
		}
		fmt.Println("init config success")
		return nil
	},
}

func init() {
	initCfgCmd.Flags().BoolVar(&initCfgCmd_Force, "force", false, "force init config")
	initCfgCmd.Flags().StringVar(&initCfgCmd_TlsCertFile, "tlsCertFile", "", "tls cert file path")
	initCfgCmd.Flags().StringVar(&initCfgCmd_TlsKeyFile, "tlsKeyFile", "", "tls key file path")
	initCfgCmd.Flags().StringVar(&initCfgCmd_Domain, "domain", "", "server domain")
	initCfgCmd.MarkFlagRequired("domain")
}
